
from langgraph.graph import END
from typing import Literal
from langchain_core.messages import RemoveMessage

from core.state import AgentState


def condition_node(state: AgentState) -> Literal["tools", END]:
    messages = state["messages"]
    # Find the last non-RemoveMessage
    last_message = None
    for msg in reversed(messages):
        if not isinstance(msg, RemoveMessage):
            last_message = msg
            break

    if not last_message:
        return END

    # If the LLM makes a tool call, route to the tools node
    if hasattr(last_message, "tool_calls") and last_message.tool_calls:
        return "tools"

    # Otherwise, end
    return END